const axios = require('axios');

/**
 * Axios工具类
 */
class AxiosUtil {

    /**
     * GET请求
     *
     * @param url
     * @param headers
     * @return {Promise<*>}
     */
    static async get(url, headers) {
        const httpRequest = AxiosUtil.buildRequest(headers, 5000);
        const response = await httpRequest.get(url, null);
        return response.data;
    }

    /**
     * GET请求
     *
     * @param url
     * @param headers
     * @param timeout
     * @return {Promise<*>}
     */
    static async getWithinTimeout(url, headers, timeout) {
        if (timeout === null) {
            timeout = 5000;
        }
        const httpRequest = AxiosUtil.buildRequest(headers, timeout);
        const response = await httpRequest.get(url, null);
        return response.data;
    }

    /**
     * POST请求
     *
     * @param url
     * @param headers
     * @param body
     * @return {Promise<*>}
     */
    static async post(url, headers, body) {
        const httpRequest = AxiosUtil.buildRequest(headers, 120000);
        const response = await httpRequest.post(url, body, null);
        return response.data;
    }

    /**
     * POST请求
     *
     * @param url
     * @param headers
     * @param body
     * @param timeout
     * @return {Promise<*>}
     */
    static async postWithinTimeout(url, headers, body, timeout) {
        if (timeout === null) {
            timeout = 10000;
        }
        const httpRequest = AxiosUtil.buildRequest(headers, timeout);
        const response = await httpRequest.post(url, body, null);
        return response.data;
    }

    /**
     * 构建请求
     *
     * @param headers
     * @param timeout
     * @return {HttpRequest}
     */
    static buildRequest(headers, timeout) {
        const httpRequest = new HttpRequest(timeout);
        if (headers != null) {
            for (let key in headers) {
                httpRequest.setHeader(key, headers[key]);
            }
        }
        return httpRequest;
    }

}

/**
 * HttpRequest
 */
class HttpRequest {

    constructor(timeout) {
        if (timeout == null) {
            timeout = 5000;
        }
        this.axiosInstance = axios.create({
            timeout: timeout,
        });
    }

    /**
     * 设置header
     *
     * @param key
     * @param value
     */
    setHeader(key, value) {
        this.axiosInstance.defaults.headers[key] = value;
    }

    /**
     * GET
     *
     * @param url
     * @param config
     * @return {Promise<axios.AxiosResponse<any>>}
     */
    get(url, config) {
        return this.axiosInstance.get(url, config);
    }

    /**
     * POST
     *
     * @param url
     * @param data
     * @param config
     * @return {Promise<axios.AxiosResponse<any>>}
     */
    post(url, data, config) {
        return this.axiosInstance.post(url, data, config);
    }
}

module.exports = {
    AxiosUtil
}